<?php
/**
 * Created by PhpStorm.
 * User: Egg
 * Date: 2018/3/20
 * Time: 9:10
 */

namespace Wechat\Model;


use Think\Model;

class ReplyLogic
{

    /**
     * 根据接收关键字获得回复内容
     * @param $keyWords 微信推送关键字
     */
    static function getReply($WxObj, $keyWords)
    {

        $replyRule = D('Admin/ReplyRule');

        $condition['rule_keywords'] = array('eq', "$keyWords");

        $replyRule->where($condition)->find();

        $rule = $replyRule->data();

        $resultD = is_array($rule) ? $rule['moudle'] : 'NONE';
        switch ($resultD) {
            case 'basic' : {
                $basicReply = D('Admin/BasicReply');
                $condition = array();
                $condition['rule_id'] = $rule['rule_id'];
                $basicReply->where($condition)->find();
                $replyContent = $basicReply->data();
                ReplyLogic::responseMsg($WxObj, $replyContent['content']);
            }
                break;
            case 'image' : {
                $basicReply = M('wx_images_reply');
                $condition = array();
                $condition['rule_id'] = $rule['rule_id'];
                $basicReply->where($condition)->find();
                $replyContent = $basicReply->data();
//                ReplyLogic::responseMsg($WxObj, $replyContent['mediaid']);

                ReplyLogic::responseImg($WxObj,$replyContent['mediaid']);

            }
                break;
            case 'music' : {

            }
                break;
            case 'news' : {

            }
                break;
            case 'video' : {

            }
                break;
            default  : {
                ReplyLogic::responseMsg($WxObj, '你在说:' . $keyWords);
            }
        }

    }


    /***
     *  回复文本消息
     * @param $WxObj    微信消息实体
     * @param $msg      返回的字符串
     */
    static function responseMsg($WxObj, $msg)
    {
        $toUser = $WxObj->FromUserName;
        $fromUser = $WxObj->ToUserName;
        $time = time();
        $str = <<<str
        <xml>
            <ToUserName><![CDATA[{$toUser}]]></ToUserName>
            <FromUserName><![CDATA[{$fromUser}]]></FromUserName>
            <CreateTime>{$time}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[{$msg}]]></Content>
        </xml>
str;
        echo $str;
        die;
    }

    /***
     * 回复图文消息
     * @param $WxObj    微信消息实体
     * @param $data     图文数组
     */
    static function responsePicAndMsg($WxObj, $data)
    {//http://lyw.iweiyun.cc/timg.jpg

        //==============造数据=============
        $item['title'] = 'Test1';
        $item['description'] = 'description1';
        $item['picurl'] = 'http://lyw.iweiyun.cc/timg.jpg';
        $item['url'] = 'http://lyw.iweiyun.cc/timg.jpg';
        //$data = array($item, $item);
        // todo 删除测试数据
        //=================================

        $toUser = $WxObj->FromUserName;
        $fromUser = $WxObj->ToUserName;
        $time = time();
        $count = count($data);

        $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>{$count}</ArticleCount>
<Articles>
str;

        foreach ($data as $item => $value) {
            $str .= <<<con
<item>
<Title><![CDATA[{$value['title']}]]></Title>
<Description><![CDATA[{$value['description']}]]></Description>
<PicUrl><![CDATA[{$value['picurl']}]]></PicUrl>
<Url><![CDATA[{$value['url']}]]></Url>
</item>
con;
        }

        $str .= '</Articles></xml>';
        echo $str;
        die;
    }

    /***
     * 回复图片消息
     * @param $WxObj    微信消息实体
     * @param $data     图片的媒体id (MediaId)
     */
    static function responseImg($WxObj, $data)
    {

        //==============造数据=============
        $item['MediaId'] = $data;

        $toUser = $WxObj->FromUserName;
        $fromUser = $WxObj->ToUserName;
        $time = time();

        $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[{$item['MediaId']}]]></MediaId>
</Image></xml>
str;

        echo $str;
        die;
    }

    /***
     * 根据事件判断回复
     * @param $WxObj    微信消息实体
     */
    static function responseEvent($WxObj)
    {
        switch ($WxObj->Event) {
            case 'CLICK': {
                WxLogic::responseClick($WxObj);
            }
                break;
            case 'subscribe': {
                WxLogic::responseSubscribe($WxObj);
            }
                break;
            default:
        }
    }

    /***
     * 回复点击事件
     * @param $WxObj    微信消息实体
     */
    static function responseClick($WxObj)
    {
        switch ($WxObj->EventKey) {
            case 'V1001': {
                WxLogic::responseMsg($WxObj, '0001');
            }
                break;
            case 'V1002': {
                $data = array(
                    array(
                        'title' => '今日新闻',
                        'description' => '新闻详情',
                        'picurl' => 'http://p0.ifengimg.com/pmop/2017/0802/C92C6DE3806D7B626E2A4FE4571C063D4486D067_size34_w640_h434.jpeg',
                        'url' => 'http://news.ifeng.com/a/20170802/51551363_0.shtml?_zbs_baidu_xk'
                    ),
                    array(
                        'title' => '风信子',
                        'description' => '风信子详情',
                        'picurl' => 'https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=0fdb0c03771ed21b6dc426b7cc07b6a1/42166d224f4a20a4ce6ca1369a529822730ed0d5.jpg',
                        'url' => 'https://baike.baidu.com/item/%E9%A3%8E%E4%BF%A1%E5%AD%90/22530?fr=aladdin'
                    ),
                    array(
                        'title' => '紫罗兰',
                        'description' => '紫罗兰详情',
                        'picurl' => 'https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike150%2C5%2C5%2C150%2C50/sign=370fce2ac41b9d169eca923392b7dfea/a71ea8d3fd1f4134d6c3598b2f1f95cad0c85e4a.jpg',
                        'url' => 'https://baike.baidu.com/item/%E7%B4%AB%E7%BD%97%E5%85%B0/5033?fr=aladdin'
                    )
                );
                WxLogic::responsePicAndMsg($WxObj, $data);
            }
                break;
            case 'V1003': {
                WxLogic::responseMsg($WxObj, '1003');
            }
                break;
            default:
        }
    }

    /***
     * 回复订阅信息
     * @param $WxObj    微信消息实体
     */
    static function responseSubscribe($WxObj)
    {
        WxLogic::responseMsg($WxObj, '欢迎订阅');
    }

    /***
     * ！！！ 弃用 ！！！
     * 发送模板信息
     * @param $openId
     * @return bool 模板是否发送成功
     */
    public function sendTemplateMsg($openId)
    {
        $url = C('url_send_template') . WxLogic::getAccessToken();
        $dataJson = $this->getTemplateJson();
        $templateId = $this->getTemplateId();
        $data = ' {
           "touser":"' . $openId . '",
           "template_id":"' . $templateId . '",
           "url":"' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '/Home/UserAuth/saleAuth?sid=2' . '", ' .
            $dataJson .
            '
       }';
        $result = HttpUtil::https_request($url, $data);
        $result = json_decode($result);
        //判断请求是否成功
        if (array_key_exists('errcode', $result) && $result['errcode'] == 0) {
            //请求成功
            return true;
        } else {
            //请求失败
            return false;
        }
    }

    /***
     * 发送模板信息
     * @param $openId
     * @return bool 模板是否发送成功
     */
    public function sendTemplateMsgs($data)
    {
        $url = C('url_send_template') . WxLogic::getAccessToken();
        $result = HttpUtil::https_request($url, $data);
        $result = json_decode($result);
        //判断请求是否成功
        if (array_key_exists('errcode', $result) && $result['errcode'] == 0) {
            //请求成功
            return true;
        } else {
            //请求失败
            return false;
        }
    }

    /***
     * 获取模板Json数据
     * @return string 模板填充数据
     */
    private function getTemplateJson()
    {
        return '"data":{
                   "first": {
                       "value":"恭喜你！",
                       "color":"#173177"
                   },
                   "pm":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "pr": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "time": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }';
    }

    /***
     * 获取模板id
     * @return string   模板id
     */
    private function getTemplateId()
    {
        return '1Q_DaQon28xzN2iPaIEv26FdXmfHkB6_cfOYypKz5oE';
    }

    /**
     * 获取access_token
     * access_token 缓存在全局变量内 7000s获取一次
     * @return string
     */
    public static function getAccessToken()
    {
        // 判断access_token是否存在全局变量中
        if (!empty($GLOBALS['access_token'])) {
            // access_token存在
            // 判断access_token是否过期
            if ((time() - $GLOBALS['access_token_time']) < ($GLOBALS['expires_in'] - 500)) {
                // 未过期直接从全局变量中取
                return $GLOBALS['access_token'];
            }
        }
        /**
         *  请求微信获取AccessToken
         *  拼接get字符串
         */
        $url = C('url_access_token')
            . C('appid') . '&secret=' . C('appsecret');

        $result = HttpUtil::httpGet($url);

        $obj = json_decode($result);
        //判断请求是否成功
        if (array_key_exists('errcode', $obj) && $result['errcode'] == 0) {
            //请求失败
            return '';
        } else {
            /**
             * 缓存 access_token，expires_in(有效时间)
             */
            $GLOBALS['access_token'] = $obj->access_token;
            $GLOBALS['expires_in'] = $obj->expires_in;
            $GLOBALS['access_token_time'] = time();
            return $obj->access_token;
        }
    }
}